package com.tuocent.dagv2.controller;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Controller
@RequestMapping("db")
public class DBController {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    private static final String resource = "config/mybatis-config-dao.xml";
    private static final String url = "jdbc:mysql://127.0.0.1:23308/dagv2_db";

    private static final String username = "dagV2_db_user";
    private static final String pwd = "q98@8Kew7LTSOJSP2";


    @RequestMapping("create")
    @ResponseBody
    public String createDB(@RequestParam(value = "tableName") String tableName) {

        FastAutoGenerator.create(url, username, pwd)
                .globalConfig(builder -> builder
                        .author("Vincent")
                        .outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java")
                        .commentDate("yyyy-MM-dd")
                )
                .packageConfig(builder -> builder
                        .parent("com.tuocent")
                        .moduleName("dagv2")
                        .entity("entity")
                        .mapper("mapper")
                        .service("service")
                        .serviceImpl("service.impl")
                        .xml("mapper.xml")
                )
                .strategyConfig(builder -> builder
                        .entityBuilder()
                        .enableLombok()
                )
                .strategyConfig(builder -> {
                    builder.addInclude(tableName) // 设置需要生成的表名
                            .addTablePrefix("t_", "c_", "db_", "sys_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
        return "创建数据成功";
    }

    @RequestMapping("showinfo")
    @ResponseBody
    public String showInfo() throws IOException {
        String appDir = System.getProperty("user.dir");
        Properties pros = new Properties();
        Map<String, String> map = new HashMap<>();
        try {
            InputStream is = new DefaultResourceLoader().getResource("file:" + appDir + "/config/das2022.yml").getInputStream();
            pros.load(is);
            Enumeration<?> en = pros.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String property = pros.getProperty(key);
                map.put(key, property);
            }
            return map.get("app.name");
        } catch (IOException e) {
            return e.getMessage();
        }

    }

    @RequestMapping("excelSQL")
    @ResponseBody
    public String excelSQL() throws SQLException {
        String sql = "insert into sys_userrole set id='5C2224B8-6BF0-477E-8057-75145DF10D14', role='临时用户'";
        SqlSession sqlSession = openSession();
        PreparedStatement pst = null;
        String msg = "";
        boolean result = false;
        try {
            pst = sqlSession.getConnection().prepareStatement(sql);
            result = pst.execute(sql);
            msg = "OK";
        } catch (SQLException e) {
            msg = e.getMessage();
            e.printStackTrace();
        } finally {
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    msg = e.getMessage();
                    e.printStackTrace();
                }
            }
            closeSession(sqlSession);
        }
        return msg;
    }

    //    开启链接
    private SqlSession openSession() {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }

    //    关闭链接
    private void closeSession(SqlSession sqlSession) {
        sqlSession.close();
    }
}
